package com.fast.security.filter;

import com.fast.security.provider.TokenProvider;
import com.fast.security.user.JwtUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Class JWTAuthFilter
 *
 * @Auther: lhy
 * @Date: 2021/12/6 18:37
 * @Mail: 190643201@qq.com
 */
public class JWTAuthFilter implements Filter {
    private static final String AUTHORIZATION_HEADER = "Authorization";
    private final TokenProvider tokenProvider;
    private final UserDetailsService userDetailsService;
    private static final Logger LOG = LoggerFactory.getLogger(JWTAuthFilter.class);

    public JWTAuthFilter(TokenProvider tokenProvider, UserDetailsService userDetailsService) {
        this.tokenProvider = tokenProvider;
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = resolveToken(httpServletRequest);
        if (StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
            // 从 token 获取 相关的 用户信息
            String username = tokenProvider.getUsernameFromToken(token);
            HttpServletResponse httpServletResponse=(HttpServletResponse) response;
            JwtUserDetails jwtUserDetails = (JwtUserDetails) this.userDetailsService.loadUserByUsername(username);
            httpServletResponse.setHeader("Access-Control-Expose-Headers","Authorization");
            //httpServletResponse.setHeader("Authorization",tokenProvider.createToken(jwtUserDetails,false));
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(jwtUserDetails, null, jwtUserDetails.getAuthorities());
            System.out.println(authentication);
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }

    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader(AUTHORIZATION_HEADER);
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
